package com.pw.study.server.tcp;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * @Author: linux_future
 * @since: 2022/4/2
 **/
public class MessageHandler implements Runnable {
    private final Socket webApp;
    private final Socket socket;
    private InputStream inSocket;
    private OutputStream outSocket;


    public MessageHandler(Socket socket, Socket webSocket) {
        this.socket = socket;
        this.webApp = webSocket;
    }

    @Override
    public void run() {
        doMessage(webApp, socket);
    }

    //数据处理
    private void doMessage(Socket webApp, Socket socket) {
        try {
            inSocket = socket.getInputStream();
            outSocket = socket.getOutputStream();
            System.out.println("开始向客户端写回数据。。。。");
           // writer.write("server ---> client: 向你回写数据。。。。。。");
            //writer.flush();
            System.out.println("server 刷写数据========");
            for (; ; ) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(inSocket, StandardCharsets.UTF_8));
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outSocket, StandardCharsets.UTF_8));
                System.out.println("----");
                String line = reader.readLine();
                System.out.println("server do message....");
                /*if(line.startsWith("http")){
                    String webStr = doWebAppMessage(line, webApp);
                    writer.write("webapp-->"+webStr);
                    writer.flush();
                }else{
                    System.out.println("其他数据。。。。。。");
                    writer.write("其他客户端=====");
                    writer.flush();
                }*/
                writer.write("其他客户端=====" + line);
                writer.flush();
                if(socket.isClosed()){
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {

        }

    }

    private String doWebAppMessage(String line, Socket webApp) {
        String webLine = null;
        try {
            BufferedWriter webWriter = new BufferedWriter(new OutputStreamWriter(webApp.getOutputStream(), StandardCharsets.UTF_8));
            BufferedReader webReader = new BufferedReader(new InputStreamReader(webApp.getInputStream(), StandardCharsets.UTF_8));
            webWriter.write("line:" + line);
            webWriter.flush();
            for (; ; ) {
                webLine = webReader.readLine();
                System.out.println("webLine: " + webLine);
                if (webLine != null) {
                    System.out.println("webApp 关闭。。。。");
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return webLine;
    }
}
